<?php

namespace App\Service;


class Math
{
    public $precision; //精度默认2

    public function __construct($num = 2)
    {
        $this->precision = $num;
    }


    /**
     * 计算多个元素的积
     * @param array $data
     * @param int $precision
     */
    public function mul($data = [])
    {
        $total = 1;

        foreach ($data as $value) {
            $total = bcmul($total, $value, $this->precision);
        }

        return $this->toPrice($total);
    }

    /**
     * 除法运算
     * @param $num
     * @param $to_num
     */
    public function div($num, $to_num)
    {
        return $this->toPrice(bcdiv($num, $to_num, $this->precision));
    }

    /**
     * 减法运算
     * @param $num
     * @param $to_num
     * @return int|string
     */
    public function sub($num, $to_num)
    {
        return $this->toPrice(bcsub($num, $to_num, $this->precision));
    }

    /**
     * 加法运算
     * @param $num
     * @param $to_num
     * @return int|string
     */
    public function add($num, $to_num)
    {
        return bcadd($num, $to_num, $this->precision);
    }


    /**
     * 去掉价格后面的0
     *
     */
    public function toPrice($num)
    {
        return (string)($num + 0);
    }


    /**
     * 返回一个0-1之内的随机数
     */
    public function get_rand()
    {
        return lcg_value();
    }

    /**
     * 数值类型的价格
     * @param $num
     * @return string
     */
    public function toInt($num)
    {
        return $num + 0;

    }
}

